package cn.weixin.service.handle.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.weixin.bussiness.model.User;
import cn.weixin.bussiness.service.UserService;
import cn.weixin.common.msg.MsgType;
import cn.weixin.common.msg.req.InputEventMessage;
import cn.weixin.common.msg.resp.OutputMessage;
import cn.weixin.common.msg.resp.OutputTextMessage;
import cn.weixin.common.util.MessageUtil;
import cn.weixin.service.handle.MessageHandler;
/**
 * 事件handler
 * @author Han
 */
@Component(MsgType.REQ_MESSAGE_TYPE_EVENT)
public class EventMessageHandler implements MessageHandler<InputEventMessage>{
	@Autowired
	private UserService userService;
	
	@Override
	public OutputMessage handle(InputEventMessage inputMessage) {
		String evtType = inputMessage.getEvent();
		if(evtType.equals(MsgType.EVENT_TYPE_SUBSCRIBE)){
			//订阅
			User user = new User();
			user.setOpenid(inputMessage.getFromUserName());
			user.setCreateTime(new Date());
			user.setUpdateTime(new Date());
			userService.save(user);
			OutputTextMessage outMsg = new OutputTextMessage();
			MessageUtil.setDefault(inputMessage, outMsg);
			outMsg.setMsgType(MsgType.RESP_MESSAGE_TYPE_TEXT);
			outMsg.setContent("谢谢您的关注，么么哒~/:<L>");
			return outMsg;
		}else if(evtType.equals(MsgType.EVENT_TYPE_UNSUBSCRIBE)){
			userService.deleteByOpenid(inputMessage.getFromUserName());
			OutputTextMessage outMsg = new OutputTextMessage();
			MessageUtil.setDefault(inputMessage, outMsg);
			outMsg.setMsgType(MsgType.RESP_MESSAGE_TYPE_TEXT);
			outMsg.setContent("byebye~");
			return outMsg;
		}else{
			OutputTextMessage outMsg = new OutputTextMessage();
			MessageUtil.setDefault(inputMessage, outMsg);
			outMsg.setMsgType(MsgType.RESP_MESSAGE_TYPE_TEXT);
			outMsg.setContent("这个好难啊，我都不认识！");
			return outMsg;
		}
	}

}
